from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.


# def send_sms_code(mobile,sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)


class SMS_CODEView(APIView):
    """
        发送短信
    """
    def get(self,request,mobile):
        #判断发送的时间间隔是否在60s内
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error':'请求过于频繁'},status=402)
        #1.获取手机号
        #2.生成短信验证码
        sms_code = ('%06d' % randint(0,999999))
        print(sms_code)
        #3.在redis保存真实短信验证码
        #生成管道
        pl = conn.pipeline()
        pl.setex('sms_code_%s' % mobile,300,sms_code)
        pl.setex('sms_code_flag_%s' % mobile,60,2)
        #连接redis传递数据
        pl.execute()
        #4.发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)
        # t = Thread(target=send_sms_code,args=(mobile,sms_code))
        # t.start()
        #celery调用
        send_sms_code.delay(mobile,sms_code)
        #5.结果返回
        return Response({'message':'ok'})
